package ;

/**
 * ...
 * @author Axel Huizinga axel@cunity.me
 */
import haxe.Http;
import hxjson2.JSON;

class Util 
{
	static var tmpObj:Dynamic = {};
	static var allIds:Array<String> = [];
	
	public static function buildMenu(id:String):Dynamic
	{
		var bObj:Dynamic = { };
		var obj:Dynamic = Reflect.field(tmpObj, id);
		for (key in Reflect.fields(obj))
		{
			if (key != 'items')
				Reflect.setField(bObj, key, Reflect.field(obj, key));
		}
		//var items:Array<Dynamic> = Reflect.field(obj, id).items;
		var items:Array<Dynamic> = obj.items;
		if (items.length > 0)
		{
			bObj.items = [];
			for (item in items)
			{
				var iObj:Dynamic = { };
				for (key in Reflect.fields(item))
				{
					if (key == 'id')
						continue;
					Reflect.setField(iObj, key, Reflect.field(item, key));
				}
				if (Lambda.has(allIds, item.id + '_'))
				{//hasSubmenu
					iObj.subMenu = buildMenu(item.id + '_');
				}
				bObj.items.push(iObj);
			}
		}
		return bObj;
	}
		
	public static function convertXml(xmlUrl:String)
	{
		tmpObj = Xml2Json.create(Http.requestUrl(xmlUrl));
		allIds = Reflect.fields(tmpObj);
		allIds.sort(
		function(a,b)
			return Reflect.compare(a.toLowerCase(), b.toLowerCase())
		);
		var menuObj:Dynamic = buildMenu(allIds.shift());
		trace('<pre>' + toString(menuObj) +'</pre>');
		var req:Http = new Http('/devel/php/save.php');
		req.async = false;
		req.setParameter('file', JSON.encode(menuObj));
		req.onData = function(data:String)
		{
			trace('saved:' + data + 'Bytes');
		}
		req.request(true);
	}
	
	public static function toString(obj:Dynamic, ind:Int = 0):String
	{
		var items:Array<Dynamic> = obj.items;
		var indent:String = '';
		var out:String = '';
		for (i in 0...ind)
			indent += ' ';
		out += indent + "{\n";
		if (items.length > 0)
		out += indent + " [\n";
		for (item in items)
		{
			for (key in Reflect.fields(item))
			{
				if (key == 'subMenu')
				{
					out +=  toString(item.subMenu, ind + 3);
				}
				else
				out += indent + '  ' + key + ':' + Reflect.field(item, key) + " ";
			}
		}
		if (items.length > 0)
		out += "\n" + indent + " ]\n";		
		out += indent + "}\n";
		return out;
	}
}